package com.bluno.view;

import java.util.LinkedList;

import com.bluno.BlunoActivity;
import com.bluno.view.obj.CardObj;
import com.bluno.view.obj.SceneObj;
import com.bluno.view.obj.TouchableObj;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class Scene extends View{

	private Paint paint;
	protected LinkedList<SceneObj> objects;
	protected LinkedList<TouchableObj> touchables;
	protected BlunoActivity mainActivity;
	protected Bitmap background;
	private int touchState;

	public Scene(Context context) {
		super(context);
		mainActivity = (BlunoActivity) context;
		objects = new LinkedList<SceneObj>();
		touchables = new LinkedList<TouchableObj>();
		paint = new Paint();
	
	}
	public void addObj(SceneObj obj)
	{
		this.objects.add(obj);
	}
	public void addTouchableObj(TouchableObj obj)
	{
		this.objects.add(obj);
		this.touchables.add(obj);
	}
	protected void removeTouchableObj(TouchableObj obj)
	{
		this.objects.remove(obj);
		this.touchables.remove(obj);	
	}
	public void update()
	{

	}
	@Override
	protected void onDraw(Canvas canvas)
	{
		
		//Draw Background
		canvas.drawBitmap(this.background, 0, 0, paint);
		//Draw and update
		for(int i = 0; i < objects.size(); ++i)
		{
			objects.get(i).draw(canvas, paint);
			objects.get(i).update();
		}
		
		//Delay
		try
		{
			Thread.sleep(30);
		}
		catch(InterruptedException e)
		{
				Log.e("Thread Error", "Scene onDraw");
		}

		//Force repaint
		invalidate(); 
	}
	/**
	 * Evento de toque de tela.
	 */
	public boolean onTouchEvent(MotionEvent event)
	{
		//mainActivity.onTouchEvent(event);
		
		for(int i = 0; i < touchables.size(); ++i)
		{
			SceneObj obj = (SceneObj)touchables.get(i);
			if(obj.testBounds(event.getX(), event.getY()) && obj.isVisible())
			{
				this.handleTouchEvent(touchables.get(i).touch(event),touchables.get(i));
			}
			else
			{
				touchables.get(i).outTouch();
			}
			
		}
		
		return true;
	}

	public int getTouchState() {
		return touchState;
	}

	public void setTouchState(int touchState) {
		this.touchState = touchState;
	}
	
	public void handleTouchEvent(int state,TouchableObj touchableObj)
	{
	}

	public Paint getPaint() {
		return paint;
	}

	public void setPaint(Paint paint) {
		this.paint = paint;
	}

	public void setTouchables(LinkedList<TouchableObj> touchables) {
		this.touchables = touchables;
	}
	
}
